﻿using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Serialization;

namespace Jack.DataScience.Data.Xml
{
    public static class XmlSerialization
    {
        public static string XmlSerialize<T>(this T obj)
        {

            XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));

            XmlSerializerNamespaces xmlNameSpaces = new XmlSerializerNamespaces();
            xmlNameSpaces.Add("", "");

            string xml = null;

            using (MemoryStream memory = new MemoryStream())
            {
                using (XmlWriter writer = XmlWriter.Create(memory, new XmlWriterSettings { OmitXmlDeclaration = true }))
                {
                    xmlSerializer.Serialize(writer, obj, xmlNameSpaces);

                    xml = Encoding.UTF8.GetString(memory.ToArray());
                }
            }

            return xml;
        }
    }
}
